from sqlalchemy import func
from sqlalchemy.orm import Session
from sqlalchemy.testing.plugin.plugin_base import options

from app.core.responses import Response
from app.database import engine
from app.schemas.music import CreateMusic, List
from app.models.user import Music as MusicModel, MusicList as MusicListModel
from app.services.orm import pagination


class Music(object):

    @staticmethod
    def index(page: int, pageSize: int):
        data = pagination(page, pageSize, MusicModel)
        with Session(engine) as session:
            random_data = session.query(MusicModel).order_by(func.random()).limit(5).all()
            print(random_data)
        return Response.success(data=data)

    @staticmethod
    def min_list(limit: int):
        with Session(engine) as session:
            random_data = session.query(MusicModel).order_by(func.random()).limit(limit).all()
        return Response.success(data={'list': random_data})

    @staticmethod
    def create(form: CreateMusic):
        with Session(engine) as session:
            music = MusicModel(**form.dict())
            session.add(music)
            session.commit()
        return True

    @staticmethod
    def delete(id: int):
        with Session(engine) as session:
            session.query(MusicModel).filter(MusicModel.id == id).delete()
            session.commit()
        return True

    @staticmethod
    def update(id: int, form: CreateMusic):
        with Session(engine) as session:
            form.id = id
            music = session.query(MusicModel).filter_by(id=id)
            music.update(form.dict())
            session.commit()
        return True

    @staticmethod
    def list_store(form: List):
        with Session(engine) as session:
            music_list = MusicListModel(**form.dict())
            session.add(music_list)
            session.commit()
        return True

    @staticmethod
    def list_index():
        with Session(engine) as session:
            data = session.query(MusicListModel).all()
            return Response.success(data={'result': data})

    @staticmethod
    def list_delete(id: int):
        with Session(engine) as session:
            session.query(MusicListModel).filter(MusicListModel.id == id).delete()
            session.commit()
        return True

    @staticmethod
    def list_update(id: int, form: List):
        with Session(engine) as session:
            form.id = id
            music = session.query(MusicListModel).filter_by(id=id)
            music.update(form.dict())
            session.commit()
        return True
